package com.mattcofer.cartoonwidget;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

/*
	Provides Dilbert cartoons to getContentResolver() calls
	http://developer.android.com/guide/topics/providers/content-providers.html
*/
public class CartoonProvider extends ContentProvider {
	public static final String TAG = "CartoonWidget";
	public static final String AUTHORITY = "com.mattcofer.cartoonwidget";

    //Matcher used to filter an incoming {@link Uri}.
    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    private static final int APPWIDGETS_CARTOONS = 103;
    private static final int APPWIDGETS_CARTOON_AT = 104;

    private static final int CARTOONS = 201;
    private static final int CARTOONS_ID = 202;

    static {
        sUriMatcher.addURI(AUTHORITY, "cartoons", CARTOONS);
        sUriMatcher.addURI(AUTHORITY, "cartoons/#", CARTOONS_ID);
    }
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
        Log.d(TAG, ".CartoonProvider$delete() with uri=" + uri);
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();

        int count = 0;

        switch (sUriMatcher.match(uri)) {
            case APPWIDGETS_CARTOONS: {
                // Delete all the forecasts for a specific widget
                long appWidgetId = Long.parseLong(uri.getPathSegments().get(1));
                if (selection == null) {
                    selection = "";
                } else {
                    selection = "(" + selection + ") AND ";
                }
                selection += CartoonsColumns.APPWIDGET_ID + "=" + appWidgetId;
                count = db.delete(TABLE_CARTOONS, selection, selectionArgs);
                break;
            }
            case CARTOONS: {
                count = db.delete(TABLE_CARTOONS, selection, selectionArgs);
                break;
            }
            default:
                throw new UnsupportedOperationException();
        }

        return count;
	}

    /**
     * {@inheritDoc}
     */
    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
            case APPWIDGETS_CARTOONS:
                return Cartoons.CONTENT_TYPE;
            case CARTOONS:
                return Cartoons.CONTENT_TYPE;
            case CARTOONS_ID:
                return Cartoons.CONTENT_ITEM_TYPE;
        }
        throw new IllegalStateException();
    }


	@Override
	public Uri insert(Uri uri, ContentValues values) {
        Log.d(TAG, "DilbertProvider$insert with values=" + values.toString());
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();

        Uri resultUri = null;

        switch (sUriMatcher.match(uri)) {
            case CARTOONS: {
                long rowId = db.insert(TABLE_CARTOONS, CartoonsColumns.URI, values);
                if (rowId != -1) {
                    resultUri = ContentUris.withAppendedId(Cartoons.CONTENT_URI, rowId);
                }
                break;
            }
            default:
                throw new UnsupportedOperationException();
        }

        return resultUri;

	}

    @Override
    public boolean onCreate() {
        mOpenHelper = new DatabaseHelper(getContext());
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
    	Log.d(TAG, "querying the database with uri=" + uri);

    	SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        String limit = null;

        switch (sUriMatcher.match(uri)) {
            case APPWIDGETS_CARTOONS: {
                // Pick the latest Uri for given widget
                String appWidgetId = uri.getPathSegments().get(1);
                qb.setTables(TABLE_CARTOONS);
                qb.appendWhere(CartoonsColumns.APPWIDGET_ID + "=" + appWidgetId);
                sortOrder = BaseColumns._ID + " DESC";
                break;
            }
            case APPWIDGETS_CARTOON_AT: {
                // Pick the latest Uri for given widget
                String appWidgetId = uri.getPathSegments().get(1);
                qb.setTables(TABLE_CARTOONS);
                qb.appendWhere(CartoonsColumns.APPWIDGET_ID + "=" + appWidgetId);
                sortOrder = BaseColumns._ID + " DESC";
                limit = "1";
                break;
            }
            case CARTOONS: {
                qb.setTables(TABLE_CARTOONS);
                break;
            }
            case CARTOONS_ID: {
                String forecastId = uri.getPathSegments().get(1);
                qb.setTables(TABLE_CARTOONS);
                qb.appendWhere(BaseColumns._ID + "=" + forecastId);
                break;
            }
        }

        return qb.query(db, projection, selection, selectionArgs, null, null, sortOrder, limit);
    }


	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs)
	{
        Log.d(TAG, "update() with uri=" + uri);
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();

        switch (sUriMatcher.match(uri)) {
            case CARTOONS: {
                return db.update(TABLE_CARTOONS, values, selection, selectionArgs);
            }
        }

        throw new UnsupportedOperationException();

	}
   
    public interface CartoonsColumns {
        /**
         * The parent {@link AppWidgetManager#EXTRA_APPWIDGET_ID} of this
         * forecast.
         */
        public static final String APPWIDGET_ID = "widgetId";

        /*
         * The unique Uri of the widget
         */
        public static final String URI = "uri";
        
        /*
         * The Url containing the updated image
         */
        public static final String URL = "url";
        
        

    }
    
    public static class Cartoons implements BaseColumns, CartoonsColumns {
        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/cartoons");

        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/cartoon";
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/cartoon";

    }

    private static final String TABLE_CARTOONS = "cartoons";

    private DatabaseHelper mOpenHelper;
    
    private static class DatabaseHelper extends SQLiteOpenHelper {
        private static final String DATABASE_NAME = "cartoons.db";

        private static final int DATABASE_VERSION = 2;

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        /*
         * (non-Javadoc)
         * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
         * Create the Database tables
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
        	Log.d(TAG, ".CartoonProvider$onCreate Creating table(s)...");

            db.execSQL("CREATE TABLE " + TABLE_CARTOONS + " ("
                    + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + CartoonsColumns.APPWIDGET_ID + " INTEGER,"
                    + CartoonsColumns.URI + " TEXT,"
                    + CartoonsColumns.URL + " TEXT);");
        }

        /*
         * (non-Javadoc)
         * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
         * Drop the database tables when upgrading the widget
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            int version = oldVersion;

            if (version != DATABASE_VERSION) {
                Log.d(TAG, ".DilbertProvider$onUpgrade Dropping old tables, if they exist");
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_CARTOONS);
                onCreate(db);
            }
        }
    }
    


}
